# -*- coding: utf-8 -*- 
import sys, os
import json
import shutil
import urllib3
import sync_card
import sync_version
import sync_activity
import sync_config
import sync_level
import notify
import refresh_configs
from jsoncompare import JsonCompare

# 体验服不同配置列表
ignore_config = {
    "CF_AndroidVersion", "CF_iOSVersion", 
    "CF_AndroidCollectSpine", "CF_iOSCollectSpine",
    "CF_AndroidBalloonSpine", "CF_iOSBalloonSpine",
    "CF_AndroidCouponPoster", "CF_iOSCouponPoster",
    "CF_AndroidSuperSerialPackSixSpine","CF_iOSSuperSerialPackSixSpine",
    "CF_AndroidCouponPosterIcon", "CF_iOSCouponPosterIcon"
}

url_config = {
    "TEST":{
        "root_url":"http://testhttp-crazyfox.superant.cc/api/config_crazy.php",
        "download_url":"http://testadmin.superant.cc/public/game/config/",
        "activity_url":"http://testadmin.superant.cc/public/game/crazyfox/activity",
        "version_url":"http://testadmin.superant.cc/public/game/crazyfox/version",
        "card_url":"http://testadmin.superant.cc/public/game/crazyfox/card",
        "level_url":"http://testadmin.superant.cc/public/game/crazyfox/level",
        "activity_cfg_url":"http://testapi.superant.cc/api/gateway.php?act=getActiveImgNameConfig&mod=Test&service=1&sid=1&lid=1",
        "local_dir":"test"
    },

    "RELEASE":{
        "root_url":"https://fox.crazyfox.vip/api/config_crazy.php",
        "download_url":"https://d3jhoo1hsyaygd.cloudfront.net/public/game/config/",
        "activity_url":"https://d3jhoo1hsyaygd.cloudfront.net/public/game/crazyfox/activity",
        "version_url":"https://d3jhoo1hsyaygd.cloudfront.net/public/game/crazyfox/version",
        "card_url":"https://d3jhoo1hsyaygd.cloudfront.net/public/game/crazyfox/card",
        "level_url":"https://d3jhoo1hsyaygd.cloudfront.net/public/game/crazyfox/level",
        "activity_cfg_url":"http://47.253.10.24/api/gateway.php?act=getActiveImgNameConfig&mod=Test&service=1&sid=1&lid=1",
        "local_dir":"release"
    },

    "AWSCDN": "d3jhoo1hsyaygd.cloudfront.net",
    "AliyunCDN": "spin.gworldtek.com"
}

# 需要检查的配置项
check_configs = [
    "AvatarBoxConfig",
    # "CardCollect",
    "CrazyBetConfig",
    "EmailPopConfig",
    "Game",
    "GiftPackageConfig",
    "GiftUpLevelConfig",
    "IconConfig",
    "LDE",
    "LEN",
    "LES",
    "LFR",
    "LID",
    "LIT",
    "LMY",
    "LNO",
    "LPT",
    "LRO",
    "LTH",
    "LVI",
    "LPL",
    "MainBgConfig",
    # "Mining",
    "NoticeMsg",
    "NoviceGuide",
    "PetConfig",
    "RecommendConfig",
    "Share",
    "UnfitnessPopConfigV2",
    "UpLimitConfig",
    "VipConfig",
    "LimitGroupTheme",
    "StopConfig",
    "SkinChestsConfig",
    "ActSkinExtraConfig",
    "TimeLimitedIslands",
    "TimeLimitedIslandsThemes",
    "BuildExchangeBlessingJson",
    "SkinChestsIdMap",
    "levelNameZH",
    "levelNameTW",
    "levelNameEN",
    "levelNameDE",
    "levelNameFR",
    "levelNameID",
    "levelNameNO",
    "levelNamePT",
    "levelNameTH",
    "levelNameVI",
    "levelNameES",
    "levelNameRO",
    "levelNameMY",
    "levelNameIT",
    "levelNamePL",
    "CardNameZH",
    "CardNameTW",
    "CardNameEN",
    "CardNameDE",
    "CardNameFR",
    "CardNameID",
    "CardNameNO",
    "CardNamePT",
    "CardNameTH",
    "CardNameVI",
    "CardNameES",
    "CardNameRO",
    "CardNameMY",
    "CardNameIT",
    "CardNamePL",
    "CardGroup",
    "CardInfo"
]

context = None

def is_download(reqtype, param, key):
    if reqtype == "prefix":
        return key.startswith(param)
    elif reqtype == "list":
        return key in param
    return True

def request_configs(conf, savePath, reqtype, param):
    """
    请求测式服的配置
    """
    http = urllib3.PoolManager()
    url = conf["root_url"]

    configs = []
    r = http.request('GET', url)
    if r.status == 200:
        resp = r.data.decode('unicode_escape')
        # print(resp)
        data = json.loads(resp)
        for (key, value) in data.items():
            if reqtype == "prefix" and key in ignore_config:
                continue

            if is_download(reqtype, param, key):
                configUrl = conf["download_url"] + value
                print("config URL: " + configUrl)

                r = http.request('GET', configUrl)
                if r.status == 200:
                    # resp = r.data.decode('unicode_escape')
                    # print(resp)
                    data = json.loads(resp)

                    target = os.path.join(savePath, key + ".json")
                    print("save path " + target)
                    configs.append(target)
                    with open(target, "wb") as fwriter:
                        fwriter.write(r.data)
                        fwriter.flush()
    return configs

def download_configs():
    cwd = os.getcwd()

    test = url_config["TEST"]
    testdir = os.path.join(cwd, "temp/" + test["local_dir"])
    print("temp dir " + testdir)
    if os.path.exists(testdir):
        shutil.rmtree(testdir)
    os.mkdir(testdir)
    testconfigs = request_configs(test, testdir, "prefix", "CF_")

    release = url_config["RELEASE"]
    releasedir = os.path.join(cwd, "temp/" + release["local_dir"])
    print("temp dir " + releasedir)
    if os.path.exists(releasedir):
        shutil.rmtree(releasedir)
    os.mkdir(releasedir)
    releaseconfigs = request_configs(release, releasedir, "prefix", "CF_")

def request_activity_configs(conf, configurls):
    """
    请求活动配置
    """
    http = urllib3.PoolManager()
    configlist = []
    keys = configurls.keys()
    for k in keys:
        configlist.append(k)

    for (url, localPath) in configurls.items():
        print("url: " + url)
        r = http.request('GET', url)
        if r.status == 200:
            # resp = r.data.decode('unicode_escape')
            # print(resp)
            print("save path " + localPath)
            with open(localPath, "wb") as fwriter:
                fwriter.write(r.data)
                fwriter.flush()
                configlist.remove(url)
    if len(configlist) > 0:
        print("\nError: download config fail：\n" + "\n".join(configlist))
    else:
        print("download config success")
    return configlist

def download_activity_configs(assets):
    """
    下载活动配置
    """
    cwd = os.getcwd()

    conf = url_config["TEST"]
    testdir = os.path.join(cwd, "temp/" + conf["local_dir"])
    print("temp dir " + testdir)
    if os.path.exists(testdir):
        shutil.rmtree(testdir)
    os.mkdir(testdir)
    config = {"CF_AndroidActivityConfig", "CF_iOSActivityConfig"}
    testconfigs = request_configs(conf, testdir, "list", config)

    platform = ""
    configurls = {}
    for key in testconfigs:
        print("=================================")
        print(key)
        childdir = testdir
        if "AndroidActivityConfig" in key:
            platform = "Android"
            childdir = os.path.join(testdir, "Android")
        else:
            platform = "iOS"
            childdir = os.path.join(testdir, "iOS")
        os.mkdir(childdir)

        with open(key, "rb") as freader:
            data = json.load(freader)
            url = url_config["RELEASE"]["activity_url"]
            for (k, v) in data.items():
                if len(v.strip()) > 0:
                    if k in assets:
                        print("key " + k + ", value " + v)
                        localdir = os.path.join(childdir, k)
                        os.mkdir(localdir)
                        configurls[os.path.join(url + "/" + platform + "/" + k + "/", v + ".json")] = os.path.join(localdir, v + ".json")
    response = request_activity_configs(conf, configurls)
    return response, configurls

def check_release_config():
    compare_config(check_configs)

def compare_config(checklist, compareValue = False):
    # 对比配置列表
    cwd = os.getcwd()

    test = url_config["TEST"]
    testdir = os.path.join(cwd, "temp/" + test["local_dir"])
    print("temp dir " + testdir)
    if os.path.exists(testdir):
        shutil.rmtree(testdir)
    os.mkdir(testdir)
    testconfigs = request_configs(test, testdir, "list", checklist)

    release = url_config["RELEASE"]
    releasedir = os.path.join(cwd, "temp/" + release["local_dir"])
    print("temp dir " + releasedir)
    if os.path.exists(releasedir):
        shutil.rmtree(releasedir)
    os.mkdir(releasedir)
    releaseconfigs = request_configs(release, releasedir, "list", checklist)

    print("test configs：\n" + "\n".join(testconfigs))
    print("release configs：\n" + "\n".join(releaseconfigs))

    if len(testconfigs) != len(releaseconfigs):
        print("ERROR: test configs.count != release configs.count")
        return

    checkResult = {}
    warning = []
    for i in range(len(checklist)):
        key = checklist[i]
        print("key " + key)
        warning.append(key)

        itemResult = []
        p1 = None
        for i in range(len(testconfigs)):
            if testconfigs[i].endswith(key + ".json"):
                p1 = testconfigs[i]
        p2 = None
        for i in range(len(releaseconfigs)):
            if releaseconfigs[i].endswith(key + ".json"):
                p2 = releaseconfigs[i]
        # print("config " + p1 + " compare " + p2)
        if (p1.endswith(key + ".json") and p2.endswith(key + ".json")):
            a = None
            with open(p1, "r", encoding="utf-8") as f1:
                a = json.load(f1)

            b = None
            with open(p2, "r", encoding="utf-8") as f2:
                b = json.load(f2)
            
            result = JsonCompare(a, b, True)
            # print(json.dumps(result.compare_result))

            for ret in result.compare_result:
                if ret["testValue"] == None or ret["releaseValue"] == None:
                    warning.append(json.dumps(ret))
                    itemResult.append(ret)
                
                if compareValue:
                    if ret["testValue"] != ret["releaseValue"]:
                        warning.append(json.dumps(ret))
                        itemResult.append(ret)
        else:
            print("ERROR: not find key " + key)
        checkResult[key] = itemResult
    
    f=open("check_config_result.txt","w")
    f.writelines("\n".join(warning))
    f.close()
    print("finished check_config_result.txt " + str(len(warning)))
    return checkResult

if __name__ == '__main__':
    print("====================================================================================")
    print("====================================================================================")

    print("method:  " + sys.argv[1])
    command = sys.argv[1]
    buildUrl = sys.argv[2]
    print("buildUrl: " + buildUrl)

    context = {
        "Deploy":command,
        "BuildJobUrl":buildUrl,
    }

    cwd = os.getcwd()
    if os.path.exists(os.path.join(cwd, "version.json")):
        os.remove(os.path.join(cwd, "version.json"))
    if os.path.exists(os.path.join(cwd, "activity.json")):
        os.remove(os.path.join(cwd, "activity.json"))
    if os.path.exists(os.path.join(cwd, "card.json")):
        os.remove(os.path.join(cwd, "card.json"))
    if os.path.exists(os.path.join(cwd, "level.json")):
        os.remove(os.path.join(cwd, "level.json"))
    
    if command == "sync_config_to_preview":
        sync_config.sync_config_to_preview(url_config, request_configs, context)
    elif command == "sync_activity_to_release":
        print("param: " + sys.argv[3])
        param = sys.argv[3]
        context["Assets"] = param
        sync_activity.sync_activity_to_release(param, url_config, download_activity_configs, context)
    elif command == "sync_version_to_release":
        print("param: " + sys.argv[3])
        param = sys.argv[3]
        context["Assets"] = param
        sync_version.sync_version_to_release(param, url_config, request_configs, context)
    elif command == "sync_card_to_release":
        print("param: " + sys.argv[3])
        param = sys.argv[3]
        context["Assets"] = param
        sync_card.sync_card_to_release(param, url_config, request_configs, context)
    elif command == "sync_level_to_release":
        print("param: " + sys.argv[3])
        param = sys.argv[3]
        context["Assets"] = param
        sync_level.sync_level_to_release(param, url_config, request_configs, context)
    elif command == "check_activity_config":
        print("param: " + sys.argv[3])
        param = sys.argv[3]
        context["Assets"] = param
        sync_activity.check_activity_config(param, compare_config, context)
    elif command == "check_release_config":
        check_release_config()
        notify.push_result(context)
    elif command == "refresh_configs":
        refresh_configs.refresh_release_configs(check_configs, url_config, request_configs, context)